<style scoped>
	.flex{
  display: flex;
}
.guide_coefficient{
    margin-right: 20px;
}
</style>

<script type="text/x-template" id="skutable">
	<div class="container">
   <div class="flex">
    <el-form class="guide_coefficient" :inline="true" :model="coefficient">
     <el-form-item label="批量市场价"  prop="guide_coefficient">
      <el-input-number :step="0.1" :min="1" :precision="2" v-model="coefficient.guide_coefficient" @keyup.enter.native.stop="setGuideCoefficient"></el-input-number>
     </el-form-item>
     <el-form-item>
      <el-button type="primary" @click="setGuideCoefficient">
       批量设置市场价
      </el-button>
     </el-form-item>
    </el-form>
    <el-form :inline="true" :model="coefficient">
     <el-form-item label="批量售价" prop="purchase_coefficient">
      <el-input-number :step="0.1" :min="1" :precision="2" v-model="coefficient.purchase_coefficient"></el-input-number>
     </el-form-item>
     <el-form-item>
      <el-button type="primary" @click="setPurchaseCoefficient">
       批量设置售价
      </el-button>
     </el-form-item>
    </el-form>
   </div>
   <egrid border="border" max-height="800" v-bind="$attrs" v-on="$listeners" :data="data" :columns="columns" :columns-props="columnsProps" :span-method="objectSpanMethod"></egrid>
</div>
</script>
<script type="text/javascript">
	function getLevels(tree) {
		let level = []
		for (let i = tree.length - 1; i >= 0; i--) {
			if (tree[i + 1] && tree[i + 1].leaf) {
				level[i] = tree[i + 1].leaf.length * level[i + 1] || 1
			} else {
				level[i] = 1
			}
		}
		return level
	}

	function isEqual(prevSKU, nextSKU, options) {
		let {
			optionValue = 'id'
		} = options || {}
		return (
			nextSKU.length === prevSKU.length &&
			nextSKU.every(({
				leaf = []
			}, index) => {
				let prevLeaf = prevSKU[index].leaf || []
				return (
					prevSKU[index][optionValue] === nextSKU[index][optionValue] &&
					leaf.length === prevLeaf.length &&
					leaf.map(item => item[optionValue]).join(',') ===
					prevLeaf.map(item => item[optionValue]).join(',')
				)
			})
		)
	}

	function flatten(tree, stocks = [], options) {
		let {
			optionValue = 'id', optionText = 'value'
		} = options || {}
		let result = []
		let skuLen = 0
		let stockMap = {} // 记录已存在的stock的数据
		const level = getLevels(tree)
		if (tree.length === 0) return result
		tree.forEach(sku => {
			const {
				leaf
			} = sku
			if (!leaf || leaf.length === 0) return true
			skuLen = (skuLen || 1) * leaf.length
		})
		// 根据已有的stocks生成一个map
		stocks.forEach(stock => {
			let {
				skus,
				...attr
			} = stock
			stockMap[skus.map(item => `${item.k_id}_${item.v_id}`).join('|')] = attr
		})
		for (let i = 0; i < skuLen; i++) {
			let skus = []
			let mapKey = []
			tree.forEach((sku, column) => {
				const {
					leaf
				} = sku
				let item = {}
				if (!leaf || leaf.length === 0) return true
				if (leaf.length > 1) {
					let row = parseInt(i / level[column], 10) % leaf.length
					item = tree[column].leaf[row]
				} else {
					item = tree[column].leaf[0]
				}
				if (!sku[optionValue] || !item[optionValue]) return
				mapKey.push(`${sku[optionValue]}_${item[optionValue]}`)
				skus.push({
					k_id: sku[optionValue],
					k: sku[optionText],
					v_id: item[optionValue],
					v: item[optionText],
				})
			})
			let { ...data
			} = stockMap[mapKey.join('|')] || {}
			// 从map中找出存在的sku并保留其值
			result.push({ ...data,
				skus
			})
		}
		return result
	}
	
	var skutableJs = {
		template: '#skutable',
		props: {
			skusData: {
				type: Array,
				default () {
					return []
				},
			},
		},
		components: {
			'egrid': egridJs
		},
		computed: {
			skusList: function skusList() {
				/**
				 * output:
				 * [
				 *   {
				 *     kvids: '1-11_2-21',
				 *     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":21,"v":"大"}],
				 *   },
				 *   {
				 *     kvids: '1-11_2-22',
				 *     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":22,"v":"小"}],
				 *   }
				 * ]
				 */
				return flatten(this.skusData).map(function(item) {
					return {
						skus: item.skus,
						kvids: item.skus.reduce(function(total, prev, index) {
							return "".concat(total).concat(prev.k_id, "-").concat(prev.v_id).concat(index === item.skus.length - 1 ?
								'' : '_');
						}, '')
					};
				});
			},
			columns: function columns() {
				var specList = this.skusData.map(function(item) {
					return {
						label: item.value,
						formater: function formater(row) {
							var sku = row.skus.find(function(sku) {
								return sku.k === item.value;
							});
							return sku.v;
						}
					};
				});
				return [].concat(_toConsumableArray(specList), [{
					label: '单位',
					width: 120,
					component: Vue.extend({
						props: ['row'],
						render: function render(createElement) {
							var _this = this;
							return createElement("el-input", {
								props: {
									value: this.row.format,
									size: "small",
								},
								attrs: {
									placeholder: "请输入单位",
								},
								on: {
									input: function oninput(e) {
										return _this.row.format = e.trim();
									}
								},
							});
						}
					})
				}, {
					label: '市场价',
					width: 150,
					component: Vue.extend({
						props: ['row'],
						render: function render(createElement) {
							var _this2 = this;
							return createElement("el-input-number", {
								props: {
									value: this.row.guidePrice,
									step: 1,
									min: 0,
									controls: false,
									precision: 2,
									size: "small",
								},
								attrs: {
									placeholder: "请输入厂家指导价",
								},
								on: {
									input: function oninput(e) {
										return _this2.row.guidePrice = e;
									}
								},
							});
						}
					})
				}, {
					label: '库存数量',
					width: 150,
					component: Vue.extend({
						props: ['row'],
						render: function render(createElement) {
							var _this3 = this;
							return createElement("el-input-number", {
								props: {
									value: this.row.count,
									step: 1,
									min: 0,
									controls: false,
									precision: 0,
									size: "small",
								},
								attrs: {
									placeholder: "请输入库存数量",
								},
								on: {
									input: function oninput(e) {
										return _this3.row.count = e;
									}
								},
							});
						}
					})
				}, {
					label: '销售价',
					width: 150,
					component: Vue.extend({
						props: ['row'],
						render: function render(createElement) {
							var _this4 = this;
							return createElement("el-input-number", {
								props: {
									value: this.row.sellPrice,
									step: 1,
									min: 0,
									controls: false,
									precision: 2,
									size: "small",
								},
								attrs: {
									placeholder: "请输入标价",
								},
								on: {
									input: function oninput(e) {
										return _this4.row.sellPrice = e;
									}
								},
							});
						}
					})
				}]);
			}
		},
		data: function() {
			return {
				data: [],
				// [
				//   {
				//     kvids: '1-11_2-21',
				//     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":21,"v":"大"}],
				//     price: '',
				//     guide: '',
				//   },
				//   {
				//     kvids: '1-11_2-22',
				//     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":22,"v":"小"}],
				//     price: '',
				//     guide: '',
				//   }
				// ]
				coefficient: {
					purchase_coefficient: 0,
					guide_coefficient: 0
				},
				columnsProps: {
					align: 'center',
					minWidth: 100
				}
			}
		},
		watch: {

			skusList: {
				deep: true,
				immediate: true,
				handler: function handler(newSkus, oldSkus) {
					var _this5 = this;

					if (!newSkus.length) return this.data = [];
					if (!oldSkus || !oldSkus.length) return this.initData(newSkus);

					if (newSkus.length === oldSkus.length) {
						// 当规格名和规格值数量未发生变化，更新 skus 即可
						return this.data = newSkus.map(function(item, index) {
							return { ..._this5.data[index],
								...item
							};
						});
					} // 当规格名的数量发生了变化


					if (newSkus[0].skus.length !== oldSkus[0].skus.length) return this.initData(newSkus);
					var diffIds = this.diffIds(newSkus, oldSkus);
					console.log("length ",newSkus.length ,oldSkus.length);
					if (newSkus.length > oldSkus.length) {
						// 当添加了规格值
						var data = [];
						newSkus.forEach(function(item) {
							var sku = _this5.data.find(function(_item) {
								console.log("skuAttributeValueDao ",_item,_item.kvids ,item.kvids);
								return (_item.kvids || _item.skuAttributeId) === item.kvids;
							});

							if (sku) {
								data.push(sku);
							} else {
								data.push({ ...item,
									format: '',
									guidePrice: 0,
									count: 0,
									sellPrice: 0
								});
							}
						});
						this.data = data;
					} else {
						// 当删除了规格值
						this.data = this.data.filter(function(_item) {
							return !diffIds.includes(_item.kvids);
						});
					}
				}
			}
		},
		methods: {

			diffIds: function diffIds(skusList1, skusList2) {
				// 两个数据的 kvids 进行相差
				skusList1 = skusList1.map(function(item) {
					return item.kvids;
				});
				skusList2 = skusList2.map(function(item) {
					return item.kvids;
				});
				return diffArary(skusList1, skusList2);
			},
			initData: function initData(skusList) {
				this.data = skusList.map(function(item) {
					return { ...item,
						// 初始化属性
						format: '',
						guidePrice: 0,
						count: 0,
						sellPrice: 0
					};
				});
			},
			objectSpanMethod: function objectSpanMethod(_ref) {
				var row = _ref.row,
					column = _ref.column,
					rowIndex = _ref.rowIndex,
					columnIndex = _ref.columnIndex;
				//console.log(row);  前行row、当前列column、当前行号rowIndex、当前列号columnIndex
				// row.skus.length 只有 sku 大于 1，才合并单元格
				// columnIndex === 0  、columnIndex === 1 ，限制只有第一列和第二列才合并单元格

				if (row.skus.length > 1 && columnIndex === 0 || row.skus.length > 2 && columnIndex === 1) {
					if (rowIndex % 2 === 0) {
						return {
							rowspan: 2,
							colspan: 1
						};
					} else {
						return {
							rowspan: 0,
							colspan: 0
						};
					}
				}
			},
			setGuideCoefficient: function setGuideCoefficient() {
				var guide_coefficient = this.coefficient.guide_coefficient;
				debugger
				this.data = this.data.map(function(item) {
					return { ...item,
						guidePrice:  guide_coefficient||0
					};
				});
			},
			setPurchaseCoefficient: function setPurchaseCoefficient() {
				var purchase_coefficient = this.coefficient.purchase_coefficient;
				this.data = this.data.map(function(item) {
					return { ...item,
						sellPrice: purchase_coefficient||0
					};
				});
			},
			getData:function(){
				return this.data;
			},
			setData:function(d){
				this.data = d;
			}
		},
		created: function() {}

	}
</script>
